#include "qrscclient.h"
#include "qhostaddress.h"
#include <QDebug>

QRSCClient::QRSCClient(QObject *parent)
    :QTcpSocket(parent)
    ,_dataSize(0)
{
    connect(this, &QTcpSocket::connected, [this]{
        qDebug() << "connected to server:" << peerAddress().toString() << ":" << peerPort();
    });

    connect(this, &QTcpSocket::disconnected, []{
        qDebug() << "disconnected to server...";
    });

    connect(this, &QTcpSocket::readyRead, [this](){
        QByteArray data = this->readAll();
        if(data.size() < 50){
            if(QString(data).startsWith("packet:")){
                this->_dataSize = QString(data).split(':').last().toInt();
                this->_imageData.clear();
                write("OK");
            }else if(QString(data).startsWith("connect")){
                //连接成功
            }
        }else{
            this->_imageData += data;
            if(this->_imageData.size() == this->_dataSize){
                QPixmap pixmap;
                pixmap.loadFromData(this->_imageData);
                this->_dataSize = 0;
                this->_imageData.clear();
                emit this->onReceiveImage(pixmap);
            }
        }
    });
}

/**
 * @name    start
 * @brief   连接服务器
 * @param   serverIp 服务器IP地址
 * @param   port     服务器端口号
 * @return  void
*/
bool QRSCClient::start(const QString &serverIp, quint16 port)
{
    if(serverIp.isEmpty() || port < 1024){
        return false;
    }
    connectToHost(serverIp, port);
    return true;
}

/**
 * @name    start
 * @brief   连接服务器
 * @param   serverIp 服务器IP地址
 * @param   port     服务器端口号
 * @return  void
*/
void QRSCClient::stop()
{
    disconnectFromHost();
    _dataSize = 0;
    _imageData.clear();
}

void QRSCClient::writeCmd(const QString &cmd)
{
      write(cmd.toUtf8().data());qDebug()<<"QRSCClient::writeCmd";
}
